import numpy as np
import matplotlib.pyplot as plt
import cv2
import get_zone_auto as gza


#读取单通道数据
name_base='./img/1106/1'
img_700_path=name_base+r' (1).PNG'
img_740_path=name_base+r' (2).PNG'
#选取小区域-避开叶脉
#rad=30
#模拟ASD 8 deg 视场角 镜头
rad=30

img_b=cv2.imread(img_700_path)
img_g=cv2.imread(img_740_path)


cv2.namedWindow('image_rawdata',cv2.WINDOW_NORMAL)
cv2.namedWindow('image_alight',cv2.WINDOW_NORMAL)
cv2.namedWindow('Trackbar',cv2.WINDOW_NORMAL)


def nothing(x):
    pass
img=img_b
print('img info:')
print('shape:',img.shape,' pixal num:',img.size/10000,'W  dtype:',img.dtype)
zeros = np.zeros(img.shape[:2], dtype = "uint8")
r     = np.zeros(img.shape[:2], dtype = "uint8")
img_res=np.zeros(img.shape[:2], dtype = "uint8")
#读取一个颜色通道
b = img_b[:,:,2]#实际上这个相机的 0  1  2是一样的
g = img_g[:,:,2]
#r = img_r[:,:,2]
rows,cols=g.shape
img=cv2.merge([b,g,r])
cv2.imshow('image_rawdata',img)
#move_B=[0,0]
move_B=[-379,-38]#1107数据
move_G=[0,0]
#move_R=[0,0]


#cv2.imwrite('./img/rgb.png',img)
p_range=1024
p_harf_range=512
#绘制滑条
cv2.createTrackbar('X','Trackbar',0,p_range,nothing)
cv2.createTrackbar('Y','Trackbar',0,p_range,nothing)
#设置滑条初始值
cv2.setTrackbarPos('X','Trackbar',p_harf_range+move_B[0])
cv2.setTrackbarPos('Y','Trackbar',p_harf_range+move_B[1])
#RGB拆分
#b,g,r=cv2.split(img)
#RGB组合br
#img2=cv2.merge([b,g,r])
def read_zone(event,x,y,flags,param):
    if event==cv2.EVENT_LBUTTONUP:
        print('>>>>move: ',move_B)
        gza.auto_read_zone(img_740_path,[x,y],rad)
        gza.auto_read_zone(img_700_path,[x-move_B[0],y-move_B[1]],rad)
    elif event==cv2.EVENT_MBUTTONDOWN:
        #print(num)
        pass
cv2.setMouseCallback('image_alight',read_zone)


while(1):
    #  main loop ==============
    move_B[0]=cv2.getTrackbarPos('X','Trackbar')-p_harf_range
    move_B[1]=cv2.getTrackbarPos('Y','Trackbar')-p_harf_range
    #构造平移矩阵
    B=np.float32([[1,0,move_B[0]],[0,1,move_B[1]]])
    G=np.float32([[1,0,move_G[0]],[0,1,move_G[1]]]) #平移矩阵  np.float32([[1,0,tx],[0,1,ty]])
    #平移图层
    B1=cv2.warpAffine(b,B,(cols,rows))
    G1=cv2.warpAffine(g,G,(cols,rows))

    img=cv2.merge([B1,G1,r])
    cv2.imshow('image_alight',img)

    #img_res=(G1/(B1+1.0))/(20/255)
    #img_res=(B1/(G1+1.0))


    
    


    #img_res=(G1-B1)/(B1+G1)*(255/10)
    #img_res=(B1-G1)*255
    ###img_res = np.array(img_res,np.uint8)
    #img_res=img_res.astype(np.uint8)
    #cv2.imshow('im_vi',img_res)
    #cv2.imshow('image_color',cv2.applyColorMap(img_res, cv2.COLORMAP_JET))

    k=cv2.waitKey(1)&0xFF
    if k==27:
        print('move: ',move_B)
        break
    if k==ord('h'):
        print('img_res  shape:',img_res.shape,'  dtype:',img_res.dtype,' max:',np.max(img_res),' min:',np.min(img_res))
        plt.hist(img_res.ravel(),255,[0,255]);
        plt.show()
        
    
cv2.destroyAllWindows()